package com.baimo.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baimo.pojo.Blog;
import com.baimo.pojo.Tag;
import com.baimo.pojo.User;
import com.baimo.service.BlogService;
import com.baimo.service.TagService;
import com.baimo.service.TypeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 白墨
 * @ClassName BlogController.java
 * @Description 博客控制层
 * @createTime 2021/4/19 22:23:40
 */
@Controller
@RequestMapping("/admin")
public class AdminBlogController {
    private static final String INPUT = "admin/blogs-input";
    private static final String LIST = "admin/blogs";
    private static final String REDIRECT_LIST = "redirect:/admin/blogs";

//    @Resource
    @Autowired
    private TypeService typeService;
//    @Resource
    @Autowired
    private BlogService blogService;
//    @Resource
    @Autowired
    private TagService tagService;
    /**
     * @description 博客展示
     * @author 白墨
     * @param model 模型
     * @param pageNum 页码
     * @updateTime 2021/4/22 2:36:07
     * @return java.lang.String
     */
    @GetMapping("/blogs")
    public String blogs(Model model,@RequestParam(defaultValue = "1",value = "pageNum")Integer pageNum) {
        setTypeAndTag(model);
        PageHelper.startPage(pageNum,10);
        List<Blog> blogs = blogService.getBlogs();
        PageInfo<Blog> pageInfo=new PageInfo<>(blogs);
        model.addAttribute("pageInfo",pageInfo);
        return AdminBlogController.LIST;
    }

    /**
     * @description 跳转到新增页面
     * @author 白墨
     * @param model 模型
     * @updateTime 2021/4/22 2:39:09
     * @return java.lang.String
     */
    @GetMapping("/blogs/input")
    public String input(Model model) {
        setTypeAndTag(model);
        model.addAttribute("blog", new Blog());
        model.addAttribute("tagIds","");
        return AdminBlogController.INPUT;
    }

    /**
     * @description 设置分类和标签
     * @author 白墨
     * @param model 模型
     * @updateTime 2021/4/22 2:38:18
     */
    private void setTypeAndTag(Model model) {
        model.addAttribute("types", typeService.getTypes());
        model.addAttribute("tags", tagService.getTags());
    }
    /**
     * @description TODO
     * @author 白墨
     * @param model 模型
     * @param pageNum 页码
     * @param blog 博客类
     * @updateTime 2021/4/22 18:39:12
     * @return java.lang.String
     */
    @PostMapping("/blogs/search")
    public String search(Model model,@RequestParam(defaultValue = "1",value = "pageNum")Integer pageNum,Blog blog) {
        setTypeAndTag(model);
        List<Blog> blogs = blogService.searchBlogs(blog);
        PageHelper.startPage(pageNum,10);
        PageInfo<Blog> pageInfo=new PageInfo<>(blogs);
        model.addAttribute("pageInfo",pageInfo);
        return AdminBlogController.LIST+" :: blogList";
    }

    /**
     * @description 发布与保存博客
     * @author 白墨
     * @param blog 博客实体类
     * @param tagIds 所有标签
     * @param attributes 转发属性
     * @param session 不用说
     * @updateTime 2021/4/22 20:58:18
     * @return java.lang.String
     */
    @PostMapping("/blogs")
    public String post(Blog blog,String tagIds, RedirectAttributes attributes, HttpSession session) {
        blog.setUser((User) session.getAttribute("user"));
        List<Tag> tags=new ArrayList<>();
        String[] split = tagIds.split(",");
        for (String s : split) {
            if (s.length()>0){
                Tag tag=new Tag();
                tag.setId(Long.parseLong(s));
                tags.add(tag);
            }
        }
        blog.setTags(tags);
        Integer result;
        if (blog.getId() == null) {
            result =  blogService.saveBlog(blog);
        } else {
            result = blogService.updateBlog(blog);
        }
        if (result >0 ) {
            attributes.addFlashAttribute("result", true);
            attributes.addFlashAttribute("message", "操作成功");
        }else {
            attributes.addFlashAttribute("result", false);
            attributes.addFlashAttribute("message", "操作失败");
        }
        return AdminBlogController.REDIRECT_LIST;
    }
    /**
     * @description 上传图片的方法
     * @author 白墨
     * @param request 请求
     * @param response 响应
     * @param attach 附件
     * @updateTime 2021/4/22 23:41:37
     * @return com.alibaba.fastjson.JSONObject
     */
    @ResponseBody
    @PostMapping("/upload")
    public JSONObject hello(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "editormd-image-file", required = false) MultipartFile attach) {
        JSONObject jsonObject=new JSONObject();
        try {
            request.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type", "text/html");

            String rootPath = ClassUtils.getDefaultClassLoader().getResource("static/image").getPath();
            /*
              文件路径不存在则需要创建文件路径
             */
            File filePath = new File(rootPath+"/blog");
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            // 最终文件名
            File realFile = new File(rootPath + File.separator + attach.getOriginalFilename());
            FileUtils.copyInputStreamToFile(attach.getInputStream(), realFile);

            // 下面response返回的json格式是editor.md所限制的，规范输出就OK

            jsonObject.put("success", 1);
            jsonObject.put("message", "上传成功");
            jsonObject.put("url", "/image/blog/"+attach.getOriginalFilename());
        } catch (Exception e) {
            jsonObject.put("success", 0);
        }

        return jsonObject;
    }

    /**
     * @description 进入修改页面
     * @author 白墨
     * @param id 博客id
     * @param model 模型
     * @updateTime 2021/4/26 2:36:50
     * @return java.lang.String
     */
    @GetMapping("/blogs/{id}/input")
    public String editInput(@PathVariable Long id, Model model) {
        setTypeAndTag(model);
        Blog blog = blogService.searchBlog(id);
        StringBuffer tagIds=new StringBuffer("");
        for (Tag tag : blog.getTags()) {
            tagIds.append(tag.getId()).append(",");
        }
        model.addAttribute("tagIds",tagIds);
        model.addAttribute("blog",blog);
        return AdminBlogController.INPUT;
    }

    /**
     * @description 删除博客
     * @author 白墨
     * @param id 博客id
     * @param attributes 转发属性
     * @updateTime 2021/4/23 2:54:34
     * @return java.lang.String
     */
    @GetMapping("/blogs/{id}/delete")
    public String delete(@PathVariable Long id,RedirectAttributes attributes) {
        Integer integer = blogService.deleteBlog(id);
        if (integer>0){
            attributes.addFlashAttribute("result", true);
            attributes.addFlashAttribute("message", "删除成功");
        }else {
            attributes.addFlashAttribute("result", false);
            attributes.addFlashAttribute("message", "删除失败");
        }
        return AdminBlogController.REDIRECT_LIST;
    }

}
